package sli.sli2.pcp.tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.IllegalBlockingModeException;
import java.security.PrivateKey;
import java.util.concurrent.ExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sli.sli2.pcp.service.LoggingService;


/**
 * Listens for incoming connections, spawns a new thread for every connected secure object
 * @author Group 8, Khassraf Roman, Mueller Robin, Zischka Stefan
 *
 */
public class TCPConnectionHandler implements Runnable {
    
    private ServerSocket serverSocket;
    private ExecutorService executor;
    private static final Logger log = LoggerFactory.getLogger(TCPConnectionHandler.class);
    private LoggingService loggingService = new LoggingService();
    private PrivateKey providerPrivateKey;
	private String pathToPubkeysFolder;
    
	public TCPConnectionHandler(ServerSocket serverSocket, ExecutorService executor, PrivateKey providerPrivateKey, String pathToPubkeysFolder) {
		this.serverSocket = serverSocket;
        this.executor = executor;
        this.providerPrivateKey = providerPrivateKey;
        this.pathToPubkeysFolder = pathToPubkeysFolder;
	}
	
    @Override
	public void run() {
		while (true) {
            try {
                Socket s = serverSocket.accept();
                log.info("New connection from {} port {} accepted", s.getInetAddress().getHostAddress(), s.getPort());
                executor.execute(new TCPThread(s, providerPrivateKey, loggingService, pathToPubkeysFolder));
            } catch (IOException | SecurityException | IllegalBlockingModeException e) {
                log.error("Failed to accept new connection", e);
            }
        }
	}

}
